//JSONP_PATH = 'http://api.meizhanggui.cc/V1.0.0/';
//JSONP_PATH = 'http://123.57.42.13/V1.0.0/';
JSONP_PATH = "http://api.meizhanggui.cc:3366/";

// 获取微信sign
g$isWX = navigator.userAgent.match(/MicroMessenger/i) != null;
var getWxSign = function () {
    var wxUrl = encodeURIComponent(location.href.split('#')[0]);
    var config = function (appId, timestamp, nonceStr, signature) {
        wx.config({
            debug: false,
            appId: appId,
            timestamp: timestamp,
            nonceStr: nonceStr,
            signature: signature,
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo'
            ]
        });
    };
    $.ajax({
        url: "http://api.meizhanggui.cc/V1.0.0/Weixin/Public/token/?_method=GET&url=" + wxUrl,
        dataType: "jsonp",
        jsonp: "callback", //传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(默认为:callback)
        jsonpCallback: "success_jsonpCallback", //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
        type: "GET",
        async: false,
        success: function (data) {
            var data = eval("(" + data + ")");
            var appId = data.data.app_id,
                timestamp = data.data.timestamp,
                nonceStr = data.data.noncestr,
                signature = data.data.signature;
            config(appId, timestamp, nonceStr, signature);
            wxready();
        }
    });
};
if (g$isWX)getWxSign();
function wxready() {
    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
        wx.checkJsApi({
            jsApiList: [
                'getNetworkType',
                'previewImage'
            ],
            success: function (res) {
                window.wxready = true;
            }
        });
    })
}

function parseTpl(tpl, res) {
    if (!tpl) return '';
    //解析变量
    var parse = function (str, val) {
        if (!str) return '';
        return str.replace(/\{([\w\.\|\/-]+)\}/g, function (flag, name) {
            var tmp, def = '',
                k, ret;
            ret = val; //console.log([flag, name]);
            if (~name.indexOf('|')) {
                tmp = name.split('|');
                def = tmp[1];
                name = tmp[0];
            }
            if (~name.indexOf('.')) {
                name = name.split('.');
                while (k = name.shift()) {
                    ret = ret[k];
                }
            } else {
                ret = ret[name];
            }
            if (typeof window[def] == 'function') {
                ret = window[def](ret);
                def = '';
            }
            return ret || def;
        });
    };
    tpl = tpl.replace(/<loadimg\s+/g, '<img '); //对图片标签还原
    //处理循环
    tpl = tpl.replace(/\{for\s+([-\w]+)\}([\s\S]*?)\{\/for\}/g, function (str, key, content) {
        var ret = ''; //console.log([str,key,content]);
        if (res[key] && res[key].length) {
            for (var i in res[key]) {
                if (typeof(res[key][i]) == 'object') {
                    ret += parse(content, res[key][i]);
                } else {
                    ret += content.replace('{v}', res[key][i]).replace('{k}', i);
                }
            }
        }
        return ret;
    });
    tpl = parse(tpl, res);
    return tpl;
}

function formatText(text) {
    return text.replace(/\|\d+(@[^\)]+)\)/g, '$1');
}

function formatTime(unixtime) {
    var str, todayStr = new Date(),
        todayUnixTime = Date.parse(todayStr.toString().replace(/ \d{1,2}:\d{1,2}:\d{1,2} /, ' 00:00:00 ')),
        nowUnixTime = Date.parse(todayStr),
        timeDiff = Math.ceil((nowUnixTime - unixtime) / 1000),
        todayTimeDiff = Math.ceil((todayUnixTime - unixtime) / 1000);
    if (timeDiff > 3600 * 120) {
        var curDate = new Date(unixtime);
        str = (curDate.getMonth() + 1) + '-' + curDate.getDate() + ' ' + curDate.getHours() + ':' + curDate.getMinutes();
    } else if (timeDiff > 3600 * 24) {
        str = Math.ceil(timeDiff / 86400) + "天前";
    } else {
        if (timeDiff > 3600) {
            str = Math.floor(timeDiff / 3600) + "小时前";
        } else if (timeDiff > 60) {
            str = Math.floor(timeDiff / 60) + "分钟前";
        } else {
            str = "刚刚";
        }
    }
    return str;
}

function toError(msg) {
    $('.main').hide();
    $('.tip').text(msg);
    $('.error').show();
}

!(function () {
    var params = {};
    try {
        params.feed_id = location.search.match(/feed_id=([^\b&]*)/)[1];
    } catch (e) {
        toError('参数似乎不太对的样子');
    }

    console.log(JSONP_PATH + 'feeds?feed_id=' + params.feed_id);
    $.jsonp({
        //url: 'http://inahoo.space/agqiowjdiwj',
        url: JSONP_PATH + 'feeds?_method=GET&feed_id=' + params.feed_id,
        dataType: "jsonp",
        callbackParameter: 'callback',
        //jsonp: 'callback',
        //jsonpCallback: "callback",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
        statusCode: {
            404: function () {
                toError('找不到你想看的东西啦!');
            },
            500: function () {
                toError('这条动态可能已经被删除了!');
            },
            200: function () {
            }
        },

        success: function (res) {
            res = JSON.parse(res);
            console.dir(res);

            if (res && (res.status == 'ok' || res.code == 0) && res.data) {
                var data = res.data,
                    imageLenth = data.image_urls && data.image_urls.length || 0;
                data.timeStr = formatTime(data.create_time);
                if (imageLenth > 1) {
                    var imgWidth, picBoxWidth = $('body').width();
                    if (picBoxWidth > 640) picBoxWidth = 640;
                    if (imageLenth > 3) {
                        imgWidth = Math.floor(picBoxWidth / 3);
                    } else {
                        imgWidth = Math.floor(picBoxWidth / 2);

                    }
                    for (var i = 0; i < imageLenth; i++) {
                        var node = '<loadimg src="' + data.image_urls[i] + '?imageView2/1/w/' + imgWidth + '/h/' + imgWidth + '"/>';
                        $('.pic-box').append(node);
                    }
                } else if (imageLenth > 0) {
                    var node = '<loadimg src="' + data.image_urls[0] + '?imageView2/1/w/640/h/640"/>';
                    $('.pic-box').append(node);
                } else {
                    $('.pic-box').hide();
                }
                window.IMGs = data.image_urls;
                if (data.tag && data.tag.length > 0) {
                    data.tagArray = data.tag.split('#');
                    if (data.tagArray.length > 3)data.tagArray = data.tagArray.slice(0, 3);
                } else {
                    $('.tagArea').hide();
                }

                console.dir(data);

                $('.main').html(parseTpl($('.main').html(), data)).show();

                if (g$isWX) {
                    window.timer = setInterval(function () {
                        if (wxready === true) {
                            $('.pic-box img').each(function (index) {
                                $(this).click(function () {
                                    wx.previewImage({
                                        current: IMGs[index],
                                        urls: IMGs
                                    });
                                });
                            });
                            clearTimeout(window.timer);
                        }
                    }, 50)
                }

                if (imageLenth > 1) {
                    $('.pic-box img').css({
                        'border': '3px solid #fff',
                        'float': 'left'
                    });
                }
                $('.pic-box img').css({
                    'width': imgWidth + 'px'
                });
                $('.main').css('padding-bottom', $('#down_banner').height() + 'px');
            } else {
                console.dir(res);
                toError(res && res.msg || '啊哦，似乎网络不给力呀！');
            }
        },

        //complete: function (a, b, c) {
        //console.log('complete');
        //console.dir(a);
        //console.dir(b);
        //console.dir(c);
        //switch (a.status) {
        //    case 200:
        //        return;
        //    case 404:
        //    {
        //        toError('啊哦，似乎网络不给力呀！');
        //    }
        //}
        //},

        error: function (a, b, c) {
            console.log('---error---');
            console.dir(a);
            console.log(b);
            console.log(c);
            //toError('这条动态可能已经被删除了!');
        }

    });

})();